package com.yenlien.traceyun.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.bean.Search;
import com.yenlien.traceyun.business.dao.SpaceBoxRecordDao;
import com.yenlien.traceyun.business.entity.SpaceBoxRecord;
import com.yenlien.traceyun.business.entity.Subpackage;
import com.yenlien.traceyun.business.interceptor.DataAuth;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.SubpackageService;
import com.yenlien.traceyun.business.service.rest.usercenter.CompanyRestService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 分包列表
 *
 * @author maybe
 * @date 2020年10月22日
 */
@RestController
@RequestMapping("/sub")
public class SubController extends BaseController {
    @Autowired
    private SubpackageService subpackageService;

    @Autowired
    private SpaceBoxRecordDao spaceBoxRecordDao;

//    @Value("${traceyun.app.id}")
    private String appId;

//    @Value("${traceyun.basePath}")
    private String basePath;
    @Autowired
    private CompanyRestService companyRestService;

    //列表页面
    @DataAuth
    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody JSONObject params) {
        Subpackage subpackage = new Subpackage();
        subpackage.setPage(params.getIntValue("page"));
        subpackage.setProductName(params.getString("productName"));
        //分包类型(生产分包、加工分包)
        subpackage.setSource(params.getString("source"));
//        subpackage.setAppId(appId);
        if (!StringUtils.isEmpty(params.getString("types")) && params.getString("types").equals("1")) {
            subpackage.setTypes(params.getString("types"));
            subpackage.setGenCoded(params.getBoolean("genCoded"));
        }
        subpackage.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        return buildPage(subpackageService.findByList(subpackage));
    }

    //分包
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(@RequestBody Subpackage subpackage) {
        subpackageService.save(subpackage);
        return success("success");
    }

    //根据关联ID查看分包列表详情
    @RequestMapping(value = "/findByRelevanceId/{id}", method = RequestMethod.GET)
    public Object findByRelevanceId(@PathVariable("id") String id) {
        return success(subpackageService.findByRelevanceId(id));
    }

    //打印
    @RequestMapping(value = "/print")
    public Object print(@RequestBody JSONObject params) {
        CheckParams.checkJson(params, new String[]{"num", "type"});
        return success(subpackageService.print(params));
    }

    //调用打码程序
    @RequestMapping(value = "/onLinePrint/{printMsgId}/{subpackageId}/{num}")
    public Object onLinePrint(@PathVariable("printMsgId") String printMsgId,
                              @PathVariable("subpackageId") String subpackageId,
                              @PathVariable("num") int num) {
        return success(subpackageService.onLinePrint(printMsgId, subpackageId, num, UserAuthUtil.getLoginUser().getCompanyId()));
    }

    //查询打印数据
    @RequestMapping(value = "/findPrintMsg/{subpackageId}", method = RequestMethod.GET)
    public Object findPrintMsg(@PathVariable("subpackageId") String subpackageId) {
        return success(subpackageService.findPrintMsg(subpackageId));
    }

    //离线打印
    @RequestMapping(value = "/offLinePrint", method = RequestMethod.POST)
    public void offLinePrint(@RequestBody JSONObject params, HttpServletResponse response, HttpServletRequest request) throws IOException {
        CheckParams.checkJson(params, new String[]{"num", "type"});
        params.put("companyId", UserAuthUtil.getLoginUser().getCompanyId());
        //生成离线码
        List<String> list = subpackageService.getCode(params);
//		response.reset();// 不加这一句的话会出现下载错误
        response.setHeader("Content-disposition", "attachment; filename=码表.txt");// 设定输出文件头
        response.setContentType("text/x-plain");// 定义输出类型
        //获取路径
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/scan/index.html?code=";
//        String basePath = "http://app.cpzsyun.com/scan/index.html?code=";
        try {
//            JSONObject parentById = (JSONObject) companyRestService.findParentById(UserAuthUtil.getLoginUser().getCompanyId());
//            JSONObject companyJson = parentById.getJSONObject("data");
//            String parentId = companyJson.getString("id");
//            if(basePath.contains("/pscan")){
//                basePath = "4028808c7fe03a4c017fe2bb6275000b".equals(parentId) ? "http://yuechi.cpzsyun.com/pscan/index.html?code=" :
//                            "4028808c7fe03a4c017fe2b7ff200006".equals(parentId) ? "http://maoxian.cpzsyun.com/pscan/index.html?code=" :
//                            "4028808c7fe03a4c017fe2b0da700001".equals(parentId) ? "http://pengzhou.cpzsyun.com/pscan/index.html?code=" : basePath;
//            }else {
//                basePath = "4028808c7fe03a4c017fe2bb6275000b".equals(parentId) ? "http://yuechi.cpzsyun.com/scan/index.html?code=" :
//                           "4028808c7fe03a4c017fe2b7ff200006".equals(parentId) ? "http://maoxian.cpzsyun.com/scan/index.html?code=" :
//                           "4028808c7fe03a4c017fe2b0da700001".equals(parentId) ? "http://pengzhou.cpzsyun.com/scan/index.html?code=" : basePath;
//            }
            JSONObject parentById = (JSONObject) companyRestService.findParentById(UserAuthUtil.getLoginUser().getCompanyId());
            String name = parentById.getJSONObject("data").getString("name");
            if(name.contains("岳池") || name.contains("茂县") || name.contains("彭州")){
                if(basePath.contains("/pscan")){
                    basePath =  name.contains("岳池") ? "http://yuechi.cpzsyun.com/pscan/index.html?code=" :
                            name.contains("茂县") ? "http://maoxian.cpzsyun.com/pscan/index.html?code=" :
                                    name.contains("彭州") ? "http://pengzhou.cpzsyun.com/pscan/index.html?code=" : basePath;
                }else {
                    basePath =  name.contains("岳池") ? "http://yuechi.cpzsyun.com/scan/index.html?code=" :
                            name.contains("茂县") ? "http://maoxian.cpzsyun.com/scan/index.html?code=" :
                                    name.contains("彭州") ? "http://pengzhou.cpzsyun.com/scan/index.html?code=" : basePath;
                }
            }

        }catch (Exception e){
            System.out.println("请求usercenter company/findParentById/ 失败");
        }
        PrintWriter writer = response.getWriter();
        for (String code : list) {
            writer.append(basePath + code + "\r\n");
        }
        writer.close();
    }

    //合格证打印获取码
    @PostMapping("/getCode")
    public Object getCode(@RequestBody JSONObject params) {
        return success(subpackageService.getCode(params));
    }

    /**
     * 申请空码
     *
     * @param spaceBoxRecord
     * @return
     */
    @PostMapping(value = "apply/spacebox")
    public Object applySpacebox(@RequestBody SpaceBoxRecord spaceBoxRecord) {
        return subpackageService.apply(spaceBoxRecord);
    }

    @PostMapping(value = "/download/h5")
    public Object downloadH5(@RequestBody SpaceBoxRecord spaceBoxRecord) {
        return subpackageService.codeH5(spaceBoxRecord);
    }

    /**
     * 获取申请空码列表
     *
     * @param search
     * @return
     */
    @PostMapping(value = "page/spacebox")
    public Object pageSpacebox(@RequestBody Search search) {
        return buildPage(subpackageService.pageSpace(search));
    }

    /**
     * 下载空码
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/spacebox/download/{id}/{batch}")
    public void download(@PathVariable("id") int id, @PathVariable("batch") String batch, HttpServletRequest request, HttpServletResponse response) throws IOException {
        subpackageService.downloadSpaceBox(id, batch, request, response);
    }

    /**
     * 空码激活
     *
     * @param params
     */
    @PostMapping(value = "spacebox/active")
    public void active(@RequestBody JSONObject params) {
        subpackageService.activeSpaceCode(params.getString("subId"), params.getJSONArray("boxs").toJavaList(String.class));
    }

    /**
     * 上传空码激活
     *
     * @param httpServletRequest
     * @return
     * @throws IOException
     */
    @PostMapping(value = "spacebox/upload")
    public Object upActive(HttpServletRequest httpServletRequest) throws IOException {
        subpackageService.uploadActive(httpServletRequest);
        return success("ok");
    }

    @PostMapping("/upPrint")
    public Object upPrint(@RequestBody JSONObject params) {
        String id = params.getString("id");
        String print = params.getString("print");
        subpackageService.upPrint(id, print);
        return success("ok");
    }

}
